package com.zdkj.subway.stm.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.beantools.CompareFileds;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.dto.in.SwStOperateLogDTO;
import com.zdkj.subway.stm.dto.out.SwStRecoveryExportDTO;
import com.zdkj.subway.stm.entity.SwStRecovery;
import com.zdkj.subway.stm.fegin.SupportService;
import com.zdkj.subway.stm.handler.LogHandler;
import com.zdkj.subway.stm.mapper.SwStRecoveryMapper;
import com.zdkj.subway.stm.service.SwStRecoveryService;
import com.zdkj.subway.stm.util.LocalDateConverter;
import com.zdkj.subway.stm.util.LocalDateTimeConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 车票回收
 *
 * @author Gofe
 * @date 2020-02-03 14:25:46
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstrecovery")
@Api(value = "swstrecovery", tags = "车票回收管理")
@Slf4j
public class SwStRecoveryController {

    private final SwStRecoveryService swStRecoveryService;
    private final SupportService supportService;
    @Resource
    SwStRecoveryMapper swStRecoveryMapper;

    /**
     * 分页查询
     *
     * @param page         分页对象
     * @param swStRecovery 车票回收
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStRecoveryPage(Page page, SwStRecovery swStRecovery) {
        List<String> dateCondition = swStRecovery.getDates1();
        QueryWrapper queryWrapper = Wrappers.query(swStRecovery);
        queryWrapper.orderByDesc("RECOVER_TIME");
        if (ObjectUtil.isNotEmpty(dateCondition)) {
            queryWrapper.apply("DATE_FORMAT(RECOVER_TIME,'%Y-%m-%d') between DATE_FORMAT('"+dateCondition.get(0)+"','%Y-%m-%d') and DATE_FORMAT('"+dateCondition.get(1)+"','%Y-%m-%d')");
        }
        if (!SecurityUtils.getUser().getBelongToLine()) {
            queryWrapper.eq("line_code", SecurityUtils.getUser().getLineCode());
            queryWrapper.eq("station_code", SecurityUtils.getUser().getStationCode());
            return R.ok(swStRecoveryService.page(page, queryWrapper));
        } else {
            return R.ok(swStRecoveryService.page(page, queryWrapper));
        }
    }


    /**
     * 通过id查询车票回收
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStRecoveryService.getById(id));
    }

    /**
     * 新增车票回收
     *
     * @param swStRecovery 车票回收
     * @return R
     */
    @ApiOperation(value = "新增车票回收", notes = "新增车票回收")
    @SysLog("新增车票回收")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_recovery_add')")
    public R save(@RequestBody SwStRecovery swStRecovery) {
        SwStRecovery defaultObj = ObjectUtils.getDefaultObj(SwStRecovery.class);
        BeanUtils.copyProperties(swStRecovery, defaultObj,
                ObjectUtils.getNullAndEmptyPropertyNames(swStRecovery));
        return R.ok(swStRecoveryService.save(defaultObj));
    }

    /**
     * 批量新增车票回收
     *
     * @param recoveryList 车票回收表
     * @return R
     */
    @ApiOperation(value = "批量新增车票回收", notes = "批量新增车票回收")
    @SysLog("批量新增车票回收")
    @PostMapping("/saveBatch")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_recovery_add_batch')")
    public R batchSave(@RequestBody List<SwStRecovery> recoveryList) {
        List<SwStRecovery> saveList = new ArrayList<>();
        recoveryList.forEach(item -> {
            SwStRecovery defaultObj = ObjectUtils.getDefaultObj(SwStRecovery.class);
            BeanUtils.copyProperties(item, defaultObj, ObjectUtils
                    .getNullAndEmptyPropertyNames(item));
            saveList.add(defaultObj);
        });
        return R.ok(swStRecoveryService.saveBatch(saveList));
    }

    /**
     * 修改车票回收
     *
     * @param swStRecovery 车票回收
     * @return R
     */
    @ApiOperation(value = "修改车票回收", notes = "修改车票回收")
    @SysLog("修改车票回收")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_recovery_edit')")
    public R updateById(@RequestBody SwStRecovery swStRecovery) {
        SwStRecovery updateObj = new SwStRecovery();
        BeanUtils.copyProperties(swStRecovery, updateObj, ObjectUtils
                .getNullAndEmptyPropertyNames(swStRecovery));
        SwStRecovery before = swStRecoveryService.getById(swStRecovery.getId());
        if (swStRecoveryService.updateById(updateObj)) {
            Map<String, Map> fileds = CompareFileds
                    .compareFields(before, swStRecovery, CompareFileds.getFileds(swStRecovery));
            if (null == fileds) {
                return R.ok();
            } else {
                List<SwStOperateLogDTO> list = LogHandler.setLogParms(fileds, before);
                return R.ok(supportService.logSaveBatch(list));
            }
        } else {
            return R.failed("修改车票回收记录失败");
        }
    }

    /**
     * 通过id删除车票回收
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除车票回收", notes = "通过id删除车票回收")
    @SysLog("通过id删除车票回收")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_recovery_del')")
    public R removeById(@PathVariable Integer id) {
        SwStRecovery swStRecovery = swStRecoveryService.getById(id);
        swStRecoveryService.removeById(swStRecovery);
        SwStOperateLogDTO swStOperateLogDTO = LogHandler.setDelLog(swStRecovery);
        return R.ok(supportService.logSave(swStOperateLogDTO));
    }

    /**
     * 批量删除车票回收
     *
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "批量删除车票回收", notes = "批量删除车票回收")
    @SysLog("批量删除车票回收")
    @DeleteMapping("/delBatch")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_recovery_del')")
    public R removeBatch(@RequestBody List<Integer> ids) {
        return R.ok(swStRecoveryService.removeByIds(ids));
    }

    /**
     * 导出车票回收信息
     *
     * @param ids
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "导出车票回收信息", notes = "导出车票回收信息")
    @GetMapping("/export")
    @SysLog("导出车票回收信息")
    //@PreAuthorize("@pms.hasPermission('stm_sw_st_recovery_export')")
    public void exportExcel(@RequestParam(value = "ids") List<Integer> ids, HttpServletResponse response) throws IOException {
        List<SwStRecoveryExportDTO> list = new ArrayList<>();
        PigxUser user = SecurityUtils.getUser();
        Map<String,String> params = new HashMap<>();
        params.put("lineCode",user.getLineCode());
        params.put("stationCode",user.getStationCode());
        List<SwStRecovery> swStRecoveryList = swStRecoveryMapper.queryExport(ids,params);
        swStRecoveryList.forEach(i -> {
            SwStRecoveryExportDTO dto = new SwStRecoveryExportDTO();
            BeanUtils.copyProperties(i, dto);
            list.add(dto);
        });

        String fileName = URLEncoder.encode("车票回收", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwStRecoveryExportDTO.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("车票回收").doWrite(list);
    }
}
